package com.ys.controller.api.account;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ys.service.flow.YspTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.account.TcwAdvanceAccountBack;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.account.TcwAdvanceAccountBackService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 预支账户归还单
 */
@Controller
@RequestMapping("/api/inter/tcwAdvanceAccountBack")
public class ApiInterTcwAdvanceAccountBackController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwAdvanceAccountBackController.class);

    @Autowired
    private CommonApiService<TcwAdvanceAccountBack> commonApiService;

    @Autowired
    private TcwAdvanceAccountBackService tcwAdvanceAccountBackService;

    @Autowired
    private YspTaskService yspTaskService;


    private final String PERMISSIONS_ADD = "tcwAdvanceAccountBack:add";

//    @RequiresPermissions("tcwAdvanceAccountBack:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TcwAdvanceAccountBack cond,String conditions){
        cond.addLeftJoin("TCW_AdvanceAccountRecharge aar ON aar.id = A.advanceAccountRechargeId ")
                .addField("aar.bid AS advanceAccountRechargeBid,aar.id advanceAccountRechargeId,aar.rechargePrice rechargePrice,aar.vjylx vjylx,aar.rechargePrice returnPrice")//充值单信息
                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS createUserName")//制单人

                .addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = aar.Vgsbm ")
                .addField("C.Vgsjc AS vgsjc,C.vgsbm AS vgsbm")//运营公司

                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = aar.CompanyVid ")
                .addField("CI.Vname AS vname")//所属公司

                .addLeftJoin("TB_CompanyBankInfo CB ON CB.Id = aar.CompanyBankInfoId ")
                .addField("CB.Vyhzhmc AS vyhzhmc")//付款账户名称
                .addField("CB.Vyhzh AS vyhzh")//付款账号
                .addField("CB.Vkhh AS vkhh")//付款开户行

                .addLeftJoin("TCW_AdvanceAccount AA ON AA.Id = aar.AdvanceAccountId ")
                .addField("AA.Code AS code")//预支账户编码
                .addField("AA.Name AS name")//付款账户名称

                /*
                .addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id")
                .addLeftJoin("TS_UserInfo B on  B.UserId = UB.UserId")
                .addField("B.DeptName AS deptName")//账户管理部门
                .addField("B.RoleName AS roleName")//负责人岗位
                .addField("(B.UserId + '/' + B.UserName) AS nameLinked")//账户管理负责人
                .addField("UB.Vyhzhmc AS vyhzhmcByAdvance")//银行账户名称
                .addField("UB.Vkhh AS vkhhByAdvance")//开户行
                .addField("UB.Vyhzh AS vyhzhByAdvance")//银行账户编码

                 */

        .addLeftJoin("TS_UserInfo B on  B.UserId = AA.UserId")
                .addLeftJoin("TS_OrganizationInfo O on  O.Orgid = AA.Orgid")
                .addField("O.DeptName AS deptName")//账户管理部门
                .addField("B.RoleName AS roleName")//负责人岗位
                .addField("(B.UserId + '/' + B.UserName) AS nameLinked")//账户管理负责人

                .addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id AND AA.AccountType=0")
                .addLeftJoin("TCW_PartnerBankInfo PB ON AA.PartnerBankInfoId = PB.Id AND AA.AccountType=1")
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vyhzhmc ELSE P.Vyhzhmc END _ys_vyhzhmc")//银行账户名称
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vkhh ELSE P.Vkhh END _ys_vkhh")//开户行
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vyhzh ELSE P.Vyhzh END _ys_vyhzh")//银行账户编码

                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vyhzhmc ELSE PB.Vyhzhmc END vyhzhmcByAdvance")//银行账户名称
                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vkhh ELSE PB.Vkhh END vkhhByAdvance")//开户行
                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vyhzh ELSE PB.Vyhzh END vyhzhByAdvance")//银行账户编码

                //明细1
                .addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByRecharge FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX000' GROUP BY Pid) D1 on D1.Pid = aar.AdvanceAccountId AND 1=1")
                .addField("ISNULL(D1.totalPriceByRecharge, 0) AS totalPriceByRecharge")//账户备用金额,字段“总额”之和（预支类型为充值）
                .addLeftJoin("TS_UserChange QWE ON QWE.Id = A.CreateChangeId")
                .addField("(QWE.UserId + '/' + QWE.UserName) AS _ys_nameLinked")//制单人

                .addLeftJoin("TS_UserInfo CU ON CU.UserId = QWE.UserId")//用户信息表
                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = CU.OrgId")//用户所属机构
                .addField("QWE.UserId AS userld")
                .addField("CU.OrgId AS orgId");

        return commonApiService.searchLay(cond);
    }


    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("预支账户归还单新增传参：" + params);
            //修改
            return tcwAdvanceAccountBackService.add(params,subData);
        } catch (Exception e) {
            logger.error("预支账户归还单新增出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("预支账户归还单修改传参：" + params);
            //修改
            return tcwAdvanceAccountBackService.edit(params,subData);
        } catch (Exception e) {
            logger.error("预支账户归还单修改出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getCause().getMessage());
        }
    }

    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwAdvanceAccountBack cond, String conditions) throws Exception{

        cond.setPage(0).setSize(999999);
        cond.addLeftJoin("TCW_AdvanceAccountRecharge aar ON aar.id = A.advanceAccountRechargeId ")
                .addField("aar.bid AS advanceAccountRechargeBid,aar.id advanceAccountRechargeId,aar.rechargePrice rechargePrice,aar.rechargePrice vjylx,aar.rechargePrice returnPrice")//充值单信息
                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS createUserName")//制单人

                .addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = aar.Vgsbm ")
                .addField("C.Vgsjc AS vgsjc,C.vgsbm AS vgsbm")//运营公司

                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = aar.CompanyVid ")
                .addField("CI.Vname AS vname")//所属公司

                .addLeftJoin("TB_CompanyBankInfo CB ON CB.Id = aar.CompanyBankInfoId ")
                .addField("CB.Vyhzhmc AS vyhzhmc")//付款账户名称
                .addField("CB.Vyhzh AS vyhzh")//付款账号
                .addField("CB.Vkhh AS vkhh")//付款开户行

                .addLeftJoin("TCW_AdvanceAccount AA ON AA.Id = aar.AdvanceAccountId ")
                .addField("AA.Code AS code")//预支账户编码
                .addField("AA.Name AS name")//付款账户名称

                .addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id")
                .addLeftJoin("TS_UserInfo B on  B.UserId = UB.UserId")
                .addField("B.DeptName AS deptName")//账户管理部门
                .addField("B.RoleName AS roleName")//负责人岗位
                .addField("(B.UserId + '/' + B.UserName) AS nameLinked")//账户管理负责人
                .addField("UB.Vyhzhmc AS vyhzhmcByAdvance")//银行账户名称
                .addField("UB.Vkhh AS vkhhByAdvance")//开户行
                .addField("UB.Vyhzh AS vyhzhByAdvance")//银行账户编码

                //明细1
                .addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByRecharge FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX000' GROUP BY Pid) D1 on D1.Pid = aar.AdvanceAccountId AND 1=1")
                .addField("ISNULL(D1.totalPriceByRecharge, 0) AS totalPriceByRecharge");//账户备用金额,字段“总额”之和（预支类型为充值）


        List<Map<String, Object>> listData = cond.queryMap();


        List<YsCol> listField = new YsCol()
                .setMenuId(MenuId.TCW_AdvanceAccountBack)
                .setFrontShow(YsColEnum.FrontShow.SHOW.value)
                .setOrderby("A.SortNo asc")
                .queryList();

        ExportExcelUtils<TcwAdvanceAccountBack> util = new ExportExcelUtils<TcwAdvanceAccountBack>(new TcwAdvanceAccountBack());

        String toFilePath = util.exportExcel(listData, listField, "预支账户归还单表");
        UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }


    /**
     * 删除预支账户归还单
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcwAdvanceAccountBackService.del(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwAdvanceAccountBackService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        try {
            return tcwAdvanceAccountBackService.flowRefuse(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        try {
            TcwAdvanceAccountBack entity = new TcwAdvanceAccountBack().setId(id).queryFirst();
            String bid = entity.getBid();
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

}
